package org.xsk.mall.api.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

/**
 * description:
 * <p>
 * date: 2021/7/14 15:16
 * author: x-one
 */
@Slf4j
public class CommandUtil {

    private static long startTime;
    private static final int DEFAULT_TIMEOUT = 5000;
    private static final int DEFAULT_INTERVAL = 100;

    public static CommandResult exec(String command){
        startTime = System.nanoTime();
        Process process = null;
        CommandResult commandResult = null;
        if (null == command || "".equals(command.trim())){
            commandResult = new CommandResult();
            commandResult.setExitValue(1);
            commandResult.setError("command is empty!");
        }
        try {
            String[] cmd;
            String osName = System.getProperty("os.name");
            if (osName.startsWith("Windows")){
                cmd = new String[3];
                if (osName.equals("Windows 95")){
                    cmd[0] = "command.com";
                }else {
                    cmd[0] = "cmd.exe";
                }
                cmd[1] = "/C";
                cmd[2] = command;
            } else if (osName.equals("Linux")){
                cmd = new String[3];
                cmd[0] = "/bin/sh";
                cmd[1] = "-c";
                cmd[2] = command;
            } else {
              cmd = new String[1];
              cmd[0] = command;
            }
            process = Runtime.getRuntime().exec(cmd);
            commandResult = wait(process);
            return commandResult;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return commandResult;
        }finally {
            if (process != null){
                process.destroy();
            }
        }
    }

    public static CommandResult wait(Process process) throws IOException, InterruptedException {

        try (BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()))
        ){
            boolean isFinished = false;
            while (true){
                if (isOverTime()){
                    CommandResult result = new CommandResult();
                    result.setExitValue(-1);
                    result.setOutput("Command process timeout!");
                    return result;
                }
                if (isFinished){
                    CommandResult result = new CommandResult();
                    result.setExitValue(process.waitFor());

                    errStringReady(error,result);
                    inputStreamReady(input,result);
                    return result;
                }
                try {
                    isFinished = true;
                    process.exitValue();
                }catch (IllegalThreadStateException e){
                    isFinished = false;
                    Thread.sleep(DEFAULT_INTERVAL);
                }
            }
        }
    }

    public static boolean isOverTime(){
        return (TimeUnit.MILLISECONDS.toNanos(DEFAULT_TIMEOUT) - (System.nanoTime() - startTime)) < 0;
    }

    private static void errStringReady(BufferedReader error,CommandResult result) throws IOException {
        if (error.ready()){
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = error.readLine()) != null){
                builder.append(line);
            }
            result.setError(builder.toString());
        }
    }

    private static void inputStreamReady(BufferedReader input , CommandResult result) throws IOException {
        if (input.ready()){
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = input.readLine()) != null){
                builder.append(line);
            }
            result.setOutput(builder.toString());
        }
    }

}
